<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\Ali\Controllers;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Doraemon\ali\model\FurnitureKeyword;
use Doraemon\tools\ImgUrl;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Tab;



class FurnitureKeywordController extends Controller
{
    const PAGE_SIZE = 10;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }


    /**
     * 家居关键词展示
     * @param Content $content
     * @return Content
     */
    public function list(Request $request,Content $content)
    {
       $params = $request->all();
       $where = [];
       if($params['id']){
           $where['id'] = $params['id'];
       }
       if($params['keyword']){
           $where['keyword'] = $params['keyword'];
       }
       if($params['show_time']['start'] && $params['show_time']['end']){
           $where['show_time[>=]'] = $params['show_time']['start'];
           $where['show_time[<=]'] = $params['show_time']['end'];
       }
        $where['keyword_status'] = FurnitureKeyword::STATUS_NORMAL;
        $where['ORDER'] = ['show_time' => 'DESC'];

        $count =  FurnitureKeyword::count($where);
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $page = $params['page'] ?? 1;
        $where['LIMIT'] =[
           ($page -1) * $page_size,
             $page_size
        ];
        $list = FurnitureKeyword::getListByWhere($where);
        $gridModel = new pGridDataModel($list ,$count , [
            'perPage' => $page_size,
        ]);
        $keywordsGrid = Admin::grid($gridModel, function (Grid $grid) use($gridModel){
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('keyword', [
                        'keyword' => '关键词',
                    ]);
                });
                $filter->column(6, function ($filter) {
                    $filter->between('show_time', '上线时间')->datetime()->condition($_GET);
                });
                $filter->expand();
            });
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->column('id');
            $grid->column('keyword', '关键词')->width(80);
            $grid->column('desc', '描述')->width(200);
            $grid->column('img', '图片')->display(function() {
                return "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $this->img, ImgUrl::IMAGE_SIZE_ORI_NPHONE)."' width=100 />";
            })->width(150);
            $grid->column("show_time" , '上线时间')->width(100);
            $grid->column("scan_count" , '浏览人数')->width(100);
            $grid->column("wiki_count" , '好物个数')->width(100);
            $grid->column("tb_link" , '淘宝链接')->width(200);
            $grid->actions(function ($action) {
//                if($action->row->show_time < date("Y-m-d 00:00:00")){
//                    $action->disableEdit();
//                }
            });
        });
        return $content->header('家居关键词')->row($keywordsGrid);
    }

    //提示信息添加页面
    public function edit(Request $request,Content $content, $id = 0)
    {

        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('')
                ->breadcrumb(
                    ['text' => '家居关键词', 'url' => '/ali/furniturekeywords/index'],
                    ['text' => '添加家居关键词', 'url' => '/ali/furniturekeywords/index/create']
                )
                ->body(self::editAction($request, $id , True));
        } else {
            return $content
                ->header('家居关键词列表')
                ->breadcrumb(
                    ['text' => '家居关键词', 'url' => '/ali/furniturekeywords/index'],
                    ['text' => '修改家居关键词', 'url' => '/ali/furniturekeywords/index/'.$id.'/edit']
                )
                ->body(self::editAction($request, $id, False));
        }
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if(!$isCreate) {
            $data = FurnitureKeyword::getByWhere(['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $form = new Form($data);
        }
        $form->text('keyword', '家居关键词')->required('不能为空');
        $form->textarea('desc', '描述')->required('不能为空');
        $form->text("tb_link" , '淘宝链接')->required('不能为空');
        $form->imgUpload('img', '图片', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
        $form->datetime("show_time" , '上线时间')->required("不能为空");

        $form->number('wiki_count')->help('好物数量')->default(0);
        $form->number('scan_count')->help('浏览数量')->default(0);
        $form->action('/admin/ali/furniturekeywords/save');
        return $form->render();
    }



    //添加、修改提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        try{
            if(empty(trim($request['keyword'])) || empty(trim($request['desc'])) ||  empty(trim($request['tb_link']) )){
                throw new \Exception('家居关键词 或 描述 或 淘宝链接 为空');
            }
            if(empty(trim($request['img']))){
                throw new \Exception('图片为空');
            }
            $data = [
                'keyword' => $request['keyword'],
                'desc' => $request['desc'],
                'img' =>$request['img'],
                'wiki_count' => $request['wiki_count'],
                'scan_count' => $request['scan_count'],
                'tb_link' => $request['tb_link'],
                'show_time' => $request['show_time'] ? :date('Y-m-d H:i:s', time()),
                'keyword_status' => FurnitureKeyword::STATUS_NORMAL,
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id,
            ];
            if(isset($request['id'])) {
                $rs = FurnitureKeyword::updateByWhere($data,['id' =>$request['id'] ]);
                if($rs) {
                    $success = new MessageBag([
                        'title' => '修改成功'
                    ]);
                    return redirect('/admin/ali/furniturekeywords/index')->with(compact('success'));
                } else {
                    $error = new MessageBag([
                        'title' => '修改失败'
                    ]);
                    return redirect('/admin/ali/furniturekeywords/index')->with(compact('error'));
                }
            } else {
                $data['addtime'] = date("Y-m-d H:i:s" , time());
                $rs = FurnitureKeyword::insert($data);
                if($rs) {
                    $success = new MessageBag([
                        'title' => '添加成功'
                    ]);
                    return redirect('/admin/ali/furniturekeywords/index')->with(compact('success'));
                } else {
                    $error = new MessageBag([
                        'title' => '添加失败'
                    ]);
                    return redirect('/admin/ali/furniturekeywords/index')->with(compact('error'));
                }
            }

        }catch (\Exception $e) {
            $error = new MessageBag([
            'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }


    }

    //删除
    public function del($id = 0)
    {
        $info = FurnitureKeyword::getByWhere(['id' => $id]);
        if($info) {
            $data = [
                'keyword_status' => FurnitureKeyword::STATUS_DELETE,
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id
            ];
            $rs = FurnitureKeyword::updateByWhere($data, ['id' => $id]);
            if($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        }

    }








}
